<template>
<div >
  <div class="search">
  <input  v-model='keywords' class="search-input" type="text" placeholder="输入城市名或拼音"/>
  </div>
  <div class="search-content" ref="search" v-show="keywords">
    <ul>
      <li
        class="search-item"
        v-for="item of list"
        :key="item.id"
        @click="handleCityClick(item.name)"
      >
        {{item.name}}
      </li>
      <li
        class="search-item"
        @click="handleCityClick('永城')"
        >
        永城
      </li>
      <li class="search-item" v-show="hasNoData">没有找到匹配数据</li>
    </ul>
  </div>
</div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keywords: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  watch: {
    keywords () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keywords) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (this.value.spell.indexOf(this.keywords) > -1 || this.value.name.indexOf(this.keywords) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style scoped lang="stylus">
  @import '~styles/varibles.styl'
  .search
    position: relative
    height: .72rem
    padding: 0 .1rem
    background:$bgColor
    .search-input
      position: absolute
      top: 0.05rem
      left:0.1rem
      right: -.1rem
      bottom:0.05rem
      font-size: .24rem
      color: #666
      height:0 .62rem
      width: 96%
      text-align: center
      padding: 0 0.2rem
      border-radius: 0.06rem
      line-height:.62rem
  .search-content
    z-index: 1
    overflow: hidden
    position: absolute
    top:1.58rem
    right:0
    bottom:0
    left: 0
    font-size:.26rem
    color: #666
    background: #eee
    .search-item
      line-height:.62rem
      padding-left:.2rem
      color: #666
      background: #fff
      border-bottom : 1px solid #ccc
</style>
